<template>
    <div class="content">
        <el-dialog :visible.sync="bindCard.dialogFormVisible" title="绑定卡片" size="small" :before-close="handleClose">
            <div v-loading = "upLoading">
                <el-form ref="ruleForm" :model="ruleForm" label-width="90px" :rules="rules">
                    <el-row :gutter="21">
                        <el-col :span="8">
                            <el-form-item label="所在地区" prop="provinceId">
                                <province v-model="ruleForm.provinceId"></province>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label=" " prop="cityId">
                                <city v-model="ruleForm.cityId" :province="ruleForm.provinceId"></city>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label=" " prop="areaId">
                                <region v-model="ruleForm.areaId" :city="ruleForm.cityId" @change="changeArea"></region>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="21">
                        <el-col>
                            <el-form-item label="学校名称" prop="schoolName">
                                <el-select v-model="ruleForm.schoolName" placeholder="请选择添加的学校" style="width:100%;" @change="schoolVerify">
                                    <el-option v-for="item in schoolList" :key="item.pId" :label="item.sName" :value="item.pId">
                                    </el-option>
                                </el-select>
                                <!--<school v-model="ruleForm.schoolName" style="width:100%" @getSchoolInfor='schoolChange' @change = "schoolVerify"></school>-->
                                <!--<el-autocomplete v-model="ruleForm.schoolName" :fetch-suggestions="remoteMethod" :trigger-on-focus="true" placeholder="请输入关键词" @select="queryAllGrade" style="width:100%"></el-autocomplete>-->
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="41">
                        <el-col>
                            <el-form-item label="教师姓名" prop="sUserName">
                                <teacherName v-model="ruleForm.sUserName" @change="queryAllName" :schoolId = "ruleForm.schoolId"></teacherName>
                                <!--<el-autocomplete v-model="ruleForm.sUserName" :fetch-suggestions="remoteMethods" :trigger-on-focus="true" placeholder="请输入关键词" @select="queryAllName(ruleForm.sUserName)" style="width:100%"></el-autocomplete>-->
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <el-row :gutter="41">
                        <el-col :span="23">
                            <el-form-item label="卡片类型" prop="sCardType">
                                <el-radio-group v-model="ruleForm.sCardType" @change="changeType">
                                    <el-radio label="0">IC卡</el-radio>
                                    <el-radio label="1">ID卡</el-radio>
                                    <el-radio label="2">双频卡</el-radio>
                                    <el-radio label="3">虚拟卡</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="41" v-if = "ruleForm.sCardType != '3'">
                        <el-col>
                            <el-form-item label="卡号" prop="cardNum">
                                <el-popover placement="top-start" trigger="focus" content="请输入卡号">
                                    <el-input slot="reference" :maxlength="10" v-model="ruleForm.cardNum" placeholder="请输入卡号"></el-input>
                                </el-popover>
                                <div class="tip">若卡面卡号以 0 开头，输入卡号时，去除前面所有的0再输入；例如：卡面卡号为【0053228075】，应输入【53228075】。</div>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="41" v-else>
                        <el-col>
                            <div>
                                <div class="vertifyTip" v-if="ruleForm.userId == ''">请先选择地区、学校，并填写教师姓名</div>
                                <el-form-item label="卡号" prop="verNum">
                                    <el-input :disabled = "true" :maxlength="10" v-model="ruleForm.verNum" placeholder="虚拟卡的卡号是系统自动生成，无需填写"></el-input>
                                    <div class="tip">虚拟卡的卡号是系统自动生成，无需填写。</div>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                    <!--<el-row>
                        <el-col :span="12">
                            <el-form-item label="卡身份">
                                <el-select v-model="ruleForm.sRelation" placeholder="请选择关系" style="width:100%;">
                                    <el-option v-for="item in relationList" :key="item.pId" :label="item.sName" :value="item.pId">
                                    </el-option>
                                </el-select>
                                <div class="tip">“管理员”身份目前只支持智慧班牌！</div>
                            </el-form-item>
                        </el-col>
                    </el-row>-->
                </el-form>
                <footer>
                    <el-button @click="cancel">取消</el-button>
                    <el-button @click="add('ruleForm')" type="primary">确认</el-button>
                </footer>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { listSchoolByArea, insertCard, getVirtualCard } from 'api/cardMangement';
import province from 'components/CascadeRegion/province';
import city from 'components/CascadeRegion/city';
import region from 'components/CascadeRegion/region';
import school from './school';
import teacherName from './teacherName';
export default {
    name: 'addClassSchool',
    components: { province, city, region, school, teacherName },
    props: {
        bindCard: {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            upLoading: false,
            gradeList: [],
            classList: [],
            schoolList: [],
            nameList: [],
            sUserNamelist: [],
            relationList: [
                {
                    pId: '',
                    sName: '全部'
                },
                {
                    pId: '1',
                    sName: '教师'
                }
                // {
                //     pId: '2',
                //     sName: '管理员'
                // },
            ],
            autoFill: false,
            ruleForm: {
                provinceId: '',
                cityId: '',
                areaId: '',
                schoolName: '',
                schoolId: '',
                sGrade: '',
                sClass: '',
                sUserName: '',
                userId: '',
                cardNum: '',
                verNum: '',
                sCardType: ''
            },
            loading: false,
            
            // 是否培训和普通学校  1 0
            schoolType: '0',
            rules: {
                provinceId: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
                cityId: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
                areaId: [
                    { required: true, message: '请选择', trigger: 'change' }
                ],
                schoolName: [
                    { required: true, message: '请输入学校名称', trigger: 'blur' }
                ],
                sGrade: [
                    { required: true, message: '请输入年级', trigger: 'change' }
                ],
                sClass: [
                    { required: true, message: '请输入班级', trigger: 'change' }
                ],
                sUserName: [
                    { required: true, message: '请输入教师姓名', trigger: 'blur' }
                ],
                cardNum: [
                    { required: true, message: '请输入卡号', trigger: 'blur' },
                    { pattern: /^[1-9]\d{0,20}$/, message: '请输入正确的卡号', trigger: 'change' }
                ],
                verNum: [
                    { required: true, message: ' ', trigger: 'blur' }
                ],
                sCardType: [{ required: true, message: '请选择卡类型', trigger: 'change' }]
            }
        };
    },
    methods: {
        changeArea(val) {
            // if (this.autoFill) return;
            this.ruleForm.schoolName = '';
            this.listSchoolByArea(val);
        },
        
        listSchoolByArea(area) {
            console.log('area', area);
            if (area === '') {
                return false;
            } else {
                this.schoolList = [];
                listSchoolByArea(this.ruleForm.provinceId, this.ruleForm.cityId, area).then(res => {
                    this.schoolList = res.data.content;
                    console.log(res.data.content);
                })
            }
        },

        schoolVerify(val) {
            if (!val) {
                this.ruleForm.sUserName = '';
            } else {
                this.getSecInfo(val);
                this.ruleForm.schoolId = val;
            }
        },

        changeType() {
            if (this.ruleForm.sCardType == '3') {
                if (this.ruleForm.schoolId !== '' && this.ruleForm.userId !== '') {
                // this.$refs['ruleForm'].validate('cardNum');
                // fUserId,
                    getVirtualCard(this.ruleForm.schoolId, this.ruleForm.userId, '1').then(res => {
                        this.ruleForm.verNum = res.data.content;
                    })
                }
            }
        },

        // 获取学校id
        // schoolChange(val) {
        // console.log('val22', this.ruleForm.schoolId !== val.schoolId);
        //     if(this.ruleForm.schoolId !== val.schoolId)
        //     {
        //         this.ruleForm.sUserName = "";
        //     }
        //     this.ruleForm.schoolId = val;
            
        //     this.getSecInfo(val);
        // },

        getSecInfo(val) {
            // 判断用户是否确认选择
            if (val) {
                if (this.ruleForm.schoolId !== val) {
                    this.ruleForm.sUserName = '';
                    return;
                }
                
            } else {
                this.schoolList = [];
                this.ruleForm.schoolName = '';
                this.ruleForm.sUserName = '';
            }

        },

        queryAllName(val) {
            this.ruleForm.userId = val;
            this.changeType();
        },

        handleClose() {
            this.$refs.ruleForm.resetFields();
            this.schoolList = [];
            this.ruleForm.schoolId = '';
            this.ruleForm.userId = '';
            this.ruleForm.cardNum = '';
            this.ruleForm.verNum = '';
            this.ruleForm.sCardType = '';
            // this.ruleForm.sRelation =  "";
            this.bindCard.dialogFormVisible = false;
        },

        add(ruleForm) {
            this.$refs[ruleForm].validate(valid => {
                if (!valid) {
                    return false;
                } else {
                    
                    // this.$message("已经添加成功，请稍等更新~");
                    // this.loading = false;
                    // this.bindCard.dialogFormVisible = false;
                    // let schoolId = '';
                    // this.schoolList.forEach(item =>{
                    //     if(this.ruleForm.schoolName == item.value){
                    //     return schoolId = item.schoolId
                    //     }
                    // });
                    // let userId = '';
                    // this.nameList.forEach(item =>{
                    //     if(this.ruleForm.sUserName == item.value){
                    //     return userId = item.fUserId;
                    //     }
                    // });
                    
                    if (this.ruleForm.userId === '' || this.ruleForm.schoolId === '' ||
                        this.ruleForm.sCardType === '' || this.ruleForm.schoolName === '') {
                        this.$message('请填写完整的信息');
                        return;
                    }
                
                    let schoolName = '';
                    this.schoolList.forEach(item => {
                        console.log('item', item);
                        if (this.ruleForm.schoolId == item.pId) {
                            console.log('item22222222', item);
                            schoolName = item.sName;
                        }
                    });
                    console.log('this.ruleForm.schoolName', schoolName);

                    this.ruleForm.cardNum = this.ruleForm.cardNum.replace(/\b(0+)/gi, '');
                    
                    let Num = '';
                    if (this.ruleForm.sCardType == '3') {
                        Num = this.ruleForm.verNum;
                    } else {
                        Num = this.ruleForm.cardNum;
                    }
                    this.upLoading = true;
                    insertCard(
                        Num,
                        this.ruleForm.userId,
                        this.ruleForm.schoolId,
                        this.ruleForm.sCardType,
                        '1',
                        schoolName,
                        '1'
                    )
                    .then(data => {
                        this.upLoading = false;
                        // this.bindCard.dialogFormVisible = false;
                        // 给父组件传值
                        this.$message({
                            message: '添加成功！',
                            type: 'success'
                        });
                        this.cancel();
                        this.$emit('bindCardState', true);
                    })
                    .catch(Error => {
                        this.upLoading = false;
                        // this.$message(Error);
                    });
                }
            });
        },

        cancel() {
            this.$refs.ruleForm.resetFields();
            this.schoolList = [];
            this.ruleForm.schoolId = '';
            this.ruleForm.userId = '';
            this.ruleForm.cardNum = '';
            this.ruleForm.verNum = '';
            this.ruleForm.sCardType = '';
            // this.ruleForm.sRelation =  "";
            this.bindCard.dialogFormVisible = false;
        }
    }
};
</script>
<style lang="scss" scoped>
.title {
  display: block;
  text-align: left;
  margin-left: 20px;
  font-size: 14px;
  margin-bottom: 18px;
  color: #333;
  position: relative;
  &::after {
    position: absolute;
    width: 4px;
    height: 14px;
    background: #ff5e2c;
    left: -15px;
    top: 10px;
    content: "";
  }
}
.vertifyTip{
    position: absolute;
    top: -25px;
    padding: 5px 0 5px 100px;
    color: #ff4949;
    font-size: 12px;
    line-height: 1;
}
.tip{
  padding: 5px 0;
  color: #ccc;
  line-height: 18px;
}
footer {
  text-align: center;
}
</style>
